#!/usr/bin/perl

use strict;
use warnings;
use POE qw(Component::IRC);
use YAML::Syck;
use FindBin;
use lib "$FindBin::Bin/lib/";
use PerlBot;

my $bot = PerlBot->new({ config => 'config.yaml' });

my $config;
if (-f 'config.yaml') {
    $config = LoadFile('config.yaml');
}

my $irc = POE::Component::IRC->spawn( 
    nick => $config->{bot}->{nickname},
    ircname => $config->{bot}->{ircname},
    server => $config->{bot}->{server},
) or die "Oh noooo! $!";


POE::Session->create(
    package_states => [
        main => [ qw(_default _start irc_001 irc_public irc_msg) ],
    ],
    heap => { irc => $irc },
);

POE::Kernel->run();

sub _start {
    my $heap = $_[HEAP];
    
    my $irc = $heap->{irc};

    $irc->yield( register => 'all' );
    $irc->yield( connect => { } );
    return;
}

sub irc_001 {
    my $sender = $_[SENDER];
    
    my $irc = $sender->get_heap();
    
    print "Connected to ", $irc->server_name(), "\n";

    $irc->yield( join => "#$_" ) for @{ $config->{bot}->{channels} };
    return;
}

sub irc_msg {
    my ($sender, $who, $where, $what) = @_[SENDER, ARG0 .. ARG2];
    my $nick = ( split /!/, $who )[0]; # )/);
    my $me = $where->[0];
    
    my $args = {
	action => 'msg',
	irc    => $irc,
	who    => $nick,
	where  => $me,
	what   => $what,
    };

    if ($what =~ /^!([a-zA-Z0-9]+)\s?(.+?)?$/) {
	my ($command, $desc) = ($1,$2);
	$args->{desc} = $desc;
	$bot->run_hook($command, $args);
    }
}

sub irc_public {
    my ($sender, $who, $where, $what) = @_[SENDER, ARG0 .. ARG2];
    my $nick = ( split /!/, $who )[0]; # )/)
    my $channel = $where->[0];

    my $args = {
	action => 'privmsg',
	irc   => $irc,
	who   => $nick,
	where => $channel,
	what  => $what,
    };

    if ($what =~ /^!([a-zA-Z0-9]+)\s?(.+?)?$/) {
	my ($command, $desc) = ($1,$2);
	$args->{desc} = $desc;
	$bot->run_hook($command, $args);
    }
    $bot->run_hook('log.write', $args);
    $bot->run_hook('log.relay', $args);
}

sub _default {
    my ($event, $args) = @_[ARG0 .. $#_];
    my @output = ( "$event: " );

    for my $arg (@$args) {
	if ( ref $arg eq 'ARRAY' ) {
	    push( @output, '[' . join(' ,', @$arg ) . ']' );
	}
	else {
	    push ( @output, "'$arg'" );
	}
    }
    print join ' ', @output, "\n";
    return 0;
}
